package com.putprize.percy.service

import javax.servlet.http.{HttpServlet,HttpServletRequest,HttpServletResponse}

import net.liftweb.json.JsonAST
import net.liftweb.json.Extraction
import net.liftweb.json.Printer
import net.liftweb.json.parse

import com.putprize.percy.PyotrInfer

class PercyInferServlet(s:PyotrService, useMeasure:Boolean) extends HttpServlet {
	
  private
  val service = s
  
  implicit val _ = net.liftweb.json.DefaultFormats
  
  def process(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    
    rp.setContentType("text/html")
    rp.setCharacterEncoding("utf-8")
    rq.setCharacterEncoding("utf-8")
    
    val line = rq.getParameter("text").toString
    
    val text = line.split(",").toArray
    
    val doc = service.parseDocument(text,useMeasure)
    
    val rs =
      if (doc.n > 1){
        val res = PyotrInfer.run(service.model,doc)
        val zs = service.getTopicScore(res._1)
        val vzs = service.getTokenScore(doc,res._2)
        Map("DOC_TOPIC"->zs,"TOKEN_TOPIC"->vzs)
      }
      else if (doc.n == 1){
        val zs = service.scoreTopicOne(doc.vs(0))
        val vzs = Map[String,Map[String,Double]]()
        Map("DOC_TOPIC"->zs,"TOKEN_TOPIC"->vzs)
      }
      else {
        val zs = Map[String,Double]()
        val vzs = Map[String,Map[String,Double]]()
        Map("DOC_TOPIC"->zs,"TOKEN_TOPIC"->vzs)
      }
    
    val data = Printer.compact(JsonAST.render(Extraction.decompose(rs)))
    
    rp.getWriter.print(data)
    
  }

  override 
  def doGet(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }
  
  override 
  def doPost(rq:HttpServletRequest, rp:HttpServletResponse):Unit = {
    process(rq,rp)
  }
  
}